import React, { Component } from 'react'
import {View, Text, Image, StatusBar, StyleSheet} from 'react-native'
import { pxToDp} from '../../utils/stylesKits'
import Icon from 'react-native-vector-icons/FontAwesome'
import { Input } from 'react-native-elements'
import {checkPhone} from '../../utils'
import request from '../../utils/request'
import { ACCOUNT_LOGIN, ACCOUNT_VALIDATEVCODE } from '../../utils/mapPath'
import THBtn from '../../components/THBtn'
import Toast from '../../utils/Toast'
import {inject,observer } from "mobx-react"
import {
  CodeField,
  Cursor
} from 'react-native-confirmation-code-field';
@inject("RootStore") // 注入 用来获取 全局数据的
@observer 
export default class index extends Component {
  state = {
    phoneNumber: '18337252813',
    phoneValid: true,
    isLogin: true,
    // 验证码框的值
    vcodeText: "",
    BtnTxt: '重新获取',
    isCountDowning: false
  }
  onVcodeChangeText = vcodeText => {
    this.setState({
      vcodeText
    })
    if(vcodeText.length===6){
      this.validCodeOnSubmitEditing(vcodeText)
    }

  }
  phoneNumberChangeText = (phoneNumber) => {
    this.setState({
      phoneNumber
    })
  }
  // 开启获取验证码的定时器
  countDown= () => {
    if(this.state.isCountDowning){
      return
    }
    this.setState({isCountDowning: true})
    let second = 5
    this.setState({
      BtnTxt: `重新获取${second}s`
    })
    let timeid = setInterval(()=> {
      --second
      this.setState({
        BtnTxt: `重新获取${second}s`
      })
      if(second===0){
        clearInterval(timeid)
        this.setState({
          BtnTxt: '重新获取',
          isCountDowning: false
        })
      }
    },1000)
  }

   phoneNumberOnSubmitEditing = async () => {
    const {phoneNumber } = this.state
    const phoneValid = checkPhone(phoneNumber)
    if (!phoneValid) {
      this.setState({phoneValid})
      return
    }
    this.setState({phoneValid})
    const res = await request.post(ACCOUNT_LOGIN, {phone: phoneNumber})
    if (res.code==='10000') {
      this.setState({isLogin: false})
      this.countDown()
    }else{
      Toast.showLoading(res.msg, 1000)
    }
  }

  validCodeOnSubmitEditing = async (vcode) => {
    const {phoneNumber} = this.state
    const res = await request.post(ACCOUNT_VALIDATEVCODE, {phone: phoneNumber, vcode:vcode})
    if(res.code !== '10000'){
      Toast.showLoading('验证码错误', 1000)
      this.setState({vcodeText: ''})
      return
    }
    console.log(res.data)
    this.props.RootStore.setUserInfo(phoneNumber, res.data.token, res.data.id)
    console.log(this.props)

    if (res.data.isNew){
      this.props.navigation.navigate('UserInfo')
    }else{
      alert('老用户')
    }
  }

  reGetvalidCode = () => {
    this.countDown()
  }

  

  render() {
    const { phoneNumber, phoneValid, isLogin, vcodeText, BtnTxt} = this.state
    return (
      <View>
        <StatusBar backgroundColor="transparent" translucent={true} />
        <Image style={{width:"100%", height: pxToDp(300)}} source={require('../../asset/bg.jpg')} />
        {isLogin? <View style={{padding: pxToDp(20)}}>
          <View>
            <View>
              <Text style={{fontSize: pxToDp(25), color: '#888', fontWeight: '800'}}>请输入账号</Text>
            </View>
            <View style={{marginTop: pxToDp(30)}}>
              <Input placeholder='请输入账号' 
              leftIcon={{type: 'font-awesome', name: 'phone', color: '#ccc', size: pxToDp(20)}}
              maxLength={11}
              keyboardType='phone-pad'
              value={phoneNumber}
              inputStyle={{color: '#333'}}
              onChangeText={this.phoneNumberChangeText}
              errorMessage={phoneValid? '': '手机号码格式不正确'}
              onSubmitEditing={this.phoneNumberOnSubmitEditing}
              />
            </View>

          </View>
          <View style={{width: '85%', height: pxToDp(40), alignSelf: 'center'}}>
            <THBtn onPress={this.phoneNumberOnSubmitEditing} style={{borderRadius: pxToDp(20)}}>点击获取验证码</THBtn>
          </View>

        </View>: <View>
          <View  style={{padding: pxToDp(20)}}>
            <Text style={{fontSize: pxToDp(25), color: '#888', fontWeight: '800'}}>输入验证码</Text>
            <View style={{marginTop: pxToDp(15)}}><Text>验证码已发送到+86{phoneNumber}</Text></View>
            <View>
              <CodeField
                value={vcodeText}
                onChangeText={this.onVcodeChangeText}
                cellCount={6}
                rootStyle={styles.codeFiledRoot}
                keyboardType="number-pad"
                renderCell={({index, symbol, isFocused}) => (
                  <Text
                    key={index}
                    style={[styles.cell, isFocused && styles.focusCell]}
                    >
                    {symbol || (isFocused ? <Cursor /> : null)}
                  </Text>
                )}
              />
            </View>
            <View 
              style={{width: '85%', height: pxToDp(40), alignSelf: 'center',marginTop: pxToDp(15)}}
            >
              <THBtn onPress={this.reGetvalidCode} style={{borderRadius: pxToDp(20)}}>{BtnTxt}</THBtn>
            </View>
          </View>
          </View>}
      </View>
    )
  }
}

const styles = StyleSheet.create({
  root: {flex: 1, padding: 20},
  title: {textAlign: 'center', fontSize: 30},
  codeFiledRoot: {marginTop: 20},
  cell: {
    width: 40,
    height: 40,
    lineHeight: 38,
    fontSize: 24,
    borderBottomWidth: 2,
    borderColor: '#00000030',
    textAlign: 'center',
    color: '#7d5cea'
  },
  focusCell: {
    borderColor: '#7d5cea',
  },
});
 
